/**
 * @Description:
 * @Author: CHEHSHUANG
 * @Date: 2019/3/13
 */
import React, {Component, Fragment} from 'react';
import {connect} from "react-redux"
import SimpleTable from "../../../commons/components/SimpleTable";
import {Button, Input, message,Modal} from "antd";
import {deleteFeature, listChildByFeatureId, saveFeature} from "./FeatureService";
import {hide, show} from "../../../configs/SharedReducer";
import ItemAddOrEditModal from "./ItemAddOrEditModal";
import CheckAuth from "../../../commons/components/CheckAuth/index.jsx";
import {searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";

const confirm=Modal.confirm;

class FeatureItemModal extends Component {
  state = {
    flag: "",
    dataSource: [],
    selectedRows: [],
    searchValue: "",
    addVisible: false
  }

  componentDidMount() {
    this.getDataSource()
  }

  onModalRef = (ref) => {
    this.modalRef = ref;
  }
  //新增或编辑点击确定按钮事件
  handleSave = () => {
    //表单数据同步
    const {parentData} = this.props;
    if (this.modalRef && this.modalRef.props.form) {
      this.modalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({confirmLoading: true, addVisible: true});
          if (this.state.flag !== "edit") {
            delete values.id
          }
          values.featureGroup = parentData.featureGroup;
          saveFeature(values).then((result) => {
            if (result.status.toUpperCase() === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              this.getDataSource();
            } else {
              message.error(result.message ? result.message : "保存失败");
            }
          }).catch(err => {
          }).finally(() => {
            this.setState({confirmLoading: false, addVisible: false});
          });
        }
      })
    }
  }
  handleCancel = () => {
    this.setState({addVisible: false})
  }
  handleSearch = (searchValue) => {
    this.setState({searchValue});
    searchListByKeyWithTag(this.state.dataSource, {keyword: searchValue}, ["code", "name"]).then(res => {
      this.setState({rightData: res, rightSearchValue: searchValue})
    })
  }
  getColumns = () => {
    return [
      {
        title: "操作",
        width: 100,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth
                operateCode="BASIC-HTPZ-GNXGL-EDIT"
              >
                <a className={'row-operator-item'} onClick={() => this.onEditClick(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth
                operateCode="BASIC-HTPZ-GNXGL-delete"
              >
                <a className={'row-operator-item'} onClick={() => this.onDeleteClick(record)}>删除</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: '代码',
        dataIndex: 'code',
        width: 240
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 200
      },
      {
        title: '资源',
        dataIndex: 'url',
        width: 200
      },
      {
        title: '功能项类型',
        dataIndex: 'featureTypeRemark',
        width: 80,
      },
    ];
  }
  getDataSource = (param = {}) => {
    this.props.show();
    const {parentData} = this.props;
    param.featureId = parentData ? parentData.id : null;
    listChildByFeatureId(param).then((result) => {
      this.setState({
        dataSource: result ? result.data : [], selectedRows: [], searchValue: ""
      });
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  }
  onAddClick = () => {
    const {parentData} = this.props;
    if (!parentData) return;
    this.setState({
      addVisible: true,
      flag: "add"
    })
  };
  onEditClick = (record) => {
    const {parentData} = this.props;
    if (!parentData || !record) return;
    this.setState({
      editData: record,
      addVisible: true,
      flag: "edit"
    })
  };
  judgeSelected = () => {
    if (!this.state.selectedRows[0]) {
      message.error('请选择一条记录！');
      return false;
    }
    return true;
  };
  onRefCreateClick = () => {
    const {parentData} = this.props;
    if (!parentData) return;
    if (!this.judgeSelected()) return;
    this.setState({
      addVisible: true,
      flag: "refAdd"
    })
  };
  onDeleteClick = (record) => {
    if (!record) return;
    let param = record.id;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk: () => {
        deleteFeature(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求table数据刷新本地数据
            this.getDataSource();
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
        })
      },
      onCancel() {
      },
    });
  };
  onSelectRow = (selectedRows) => {
    this.setState({selectedRows, editData: selectedRows[0]});
  };
  title = () => {
    return [
      <CheckAuth
        operateCode="BASIC-HTPZ-GNXGL-ADD"
        key="addRule"
      >
        <Button className={"primaryButton"} type={"primary"}
                onClick={this.onAddClick}>新增</Button>
      </CheckAuth>,
      <CheckAuth
        operateCode="BASIC-HTPZ-GNXGL-REF"
        key="rightRef"
      >
        <Button
          onClick={this.onRefCreateClick}>参考创建</Button>
      </CheckAuth>
    ]
  };

  //表头搜索框
  search = () => {
    return [
      <Input.Search
        key="search"
        placeholder="输入名称或代码进行查询"
        onSearch={this.handleSearch}
        style={{width: 220}}
        allowClear
      />
    ]
  };

  render() {
    const {parentData, visible, onCancel} = this.props;
    const title = parentData ? `功能项(操作级)>所属页面【${parentData.name}】` : "配置操作级功能项";
    const {addVisible,searchValue, dataSource,selectedRows,confirmLoading, editData, flag} = this.state;
    return (
      <Fragment>
        <Modal
          centered={true}
          title={title}
          visible={visible}
          onCancel={onCancel}
          width={1000}
          maskClosable={false}
          footer={null}
          destroyOnClose={true}
        >
          <div className={'tbar-box'}>
            <div>{this.title()}</div>
            <div className={"tbar-right"}>{this.search()}</div>
          </div>
          <SimpleTable
            inCard={true}
            data={searchValue ? dataSource.filter(item => item.tag === true) : dataSource}
            columns={this.getColumns()}
            onSelectRow={this.onSelectRow}
            rowsSelected={selectedRows}
          />
        </Modal>
        {
          addVisible ? <ItemAddOrEditModal
            addVisible={addVisible}
            confirmLoading={confirmLoading}
            handleOk={this.handleSave}
            handleCancel={this.handleCancel}
            onRef={this.onModalRef}
            parentData={parentData}
            defaultValue={editData ? editData : {}}
            flag={flag}
          /> : null
        }
      </Fragment>
    );
  }
}

const mapStateToProps = () => {
  return {}
};
const mapDispatchToProps = {show, hide};
export default connect(mapStateToProps, mapDispatchToProps)(FeatureItemModal);
